package cn.car91.activity;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import cn.car91.R;
import cn.car91.adapter.SearchItemsAdapter;
import cn.car91.adapter.SearchItemsAdapter.SearchItemInfo;
import cn.car91.bean.Article;
import cn.car91.bean.Exposure;
import cn.car91.bean.RepairShop;
import cn.car91.http.HttpHandler;
import cn.car91.utils.Car91JsonUtil;
import cn.car91.view.XListView;

import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.lidroid.xutils.view.annotation.event.OnItemClick;

public class SearchActivity extends BaseActivity {

	//public static final String searchAction = "search.change.broadcast.action";
	
    @ViewInject(R.id.search_item)
    RadioGroup typeGroup;
    @ViewInject(R.id.search_key)
    EditText keyText;
    @ViewInject(R.id.imgBtn_search_submit)
    ImageButton searchBtn;
    @ViewInject(R.id.search_result)
    XListView searchListView;

    //int type = R.id.search_item_repairshop;

    private SearchItemsAdapter adapter;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        setContentView(R.layout.activity_search);
        super.onCreate(savedInstanceState);

        adapter = new SearchItemsAdapter(SearchActivity.this, R.layout.view_search_repairshop_item);
        searchListView.setAdapter(adapter);
        
        //keyText.addTextChangedListener(keyWatcher);
        keyText.setOnEditorActionListener(new AutoCompleteTextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView AutoCompleteTextView, int arg1, KeyEvent arg2) {
                if (arg1 == EditorInfo.IME_ACTION_SEND || arg1 == EditorInfo.IME_ACTION_SEARCH
                        || (arg2 != null && arg2.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    onSearchClick(searchBtn);
                    return true;
                }
                return false;
            }
        });
        typeGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup arg0, int arg1) {
                // TODO Auto-generated method stub
                onSearchClick(searchBtn);
            }
        });
        ((TextView) findViewById(R.id.header_text)).setText("搜索");
    }

    /*@Override
    protected void onStart() {
        // TODO Auto-generated method stub
        RadioButton checkButton = (RadioButton) typeGroup.findViewById(R.id.search_item_repairshop);
        if(item!=null){
	        if (item.equals("repairshop")) {
	            checkButton = (RadioButton) typeGroup.findViewById(R.id.search_item_repairshop);
	        } else if (item.equals("article")) {
	            checkButton = (RadioButton) typeGroup.findViewById(R.id.search_item_article);
	        } else if (item.equals("exposure")) {
	            checkButton = (RadioButton) typeGroup.findViewById(R.id.search_item_exposure);
	        }
	        checkButton.setChecked(true);
        }
        super.onStart();
    }*/

    /*private void changeSearchItem() {
        for (int i = 0; i < typeGroup.getChildCount(); i++) {
            try {
                RadioButton radioButton = (RadioButton) typeGroup.getChildAt(i);
                radioButton.setTextColor(getResources().getColor(android.R.color.darker_gray));
            } catch (Exception e) {
                continue;
            }
        }

        type = typeGroup.getCheckedRadioButtonId();
        RadioButton radioButton = (RadioButton) typeGroup.findViewById(type);
        radioButton.setTextColor(getResources().getColor(R.color.theme_color));
    }*/
    
    RequestCallBack callBackSearch = new RequestCallBack() {

        @Override
        public void onFailure(HttpException arg0, String arg1) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onSuccess(ResponseInfo arg0) {
            // TODO Auto-generated method stub
            try {
                List<SearchItemInfo> searchItems = new ArrayList<SearchItemInfo>();
                int type = typeGroup.getCheckedRadioButtonId();
                switch (type) {
                    case R.id.search_item_repairshop:
                        List<RepairShop> repairShops = Car91JsonUtil.getDTOList(arg0.result.toString(), RepairShop.class);
                        for (RepairShop repairShop : repairShops) {
                            SearchItemInfo searchItemInfo = new SearchItemInfo();
                            searchItemInfo.setId(repairShop.getId());
                            searchItemInfo.setName(repairShop.getName());
                            searchItemInfo.setOther(repairShop.getDetail().getAddress());
                            searchItems.add(searchItemInfo);
                        }
                        break;
                    case R.id.search_item_article:
                        List<Article> articles = Car91JsonUtil.getDTOList(arg0.result.toString(), Article.class);
                        for (Article article : articles) {
                            SearchItemInfo searchItemInfo = new SearchItemInfo();
                            searchItemInfo.setId(String.valueOf(article.getAid()));
                            searchItemInfo.setName(article.getTitle());
                            searchItemInfo.setOther("");
                            searchItems.add(searchItemInfo);
                        }
                        break;
                    case R.id.search_item_exposure:
                        List<Exposure> exposures = Car91JsonUtil.getDTOList(arg0.result.toString(), Exposure.class);
                        for (Exposure exposure : exposures) {
                            SearchItemInfo searchItemInfo = new SearchItemInfo();
                            searchItemInfo.setId(String.valueOf(exposure.getEid()));
                            searchItemInfo.setName(exposure.getTitle());
                            searchItemInfo.setOther(exposure.getName());
                            searchItems.add(searchItemInfo);
                        }
                        break;
                    default:
                        break;
                }
                adapter.setSearchItems(searchItems);
                adapter.notifyDataSetChanged();
            } catch (Exception e) { }
        }
    };

    @OnItemClick(R.id.search_result)
    public void onSearchItemClickListener(AdapterView<?> arg0, View arg1, int arg2,
                                          long arg3) {
        // TODO Auto-generated method stub
        Intent intent = new Intent();
        int type = typeGroup.getCheckedRadioButtonId();
        switch (type) {
            case R.id.search_item_repairshop:
                //popupWindow.dismiss();
                intent.putExtra("rid", adapter.getSearchItemId((int) arg3));
                intent.setClass(SearchActivity.this, RepairShopDetailActivity.class);
                startActivity(intent);
                break;
            case R.id.search_item_article:
                intent.putExtra("aid", adapter.getSearchItemId((int) arg3));
                intent.setClass(SearchActivity.this, ArticleDetailActivity.class);
                startActivity(intent);
                break;
            case R.id.search_item_exposure:
                intent.putExtra("eid", adapter.getSearchItemId((int) arg3));
                intent.setClass(SearchActivity.this, ExposureDetailActivity.class);
                startActivity(intent);
                break;
            default:
                break;
        }
        //finish();
    }

    @OnClick(R.id.imgBtn_search_submit)
    public void onSearchClick(View view) {
        if (keyText.getEditableText().toString().getBytes().length >= 4) {
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);  
            if (imm != null) {  
                imm.hideSoftInputFromWindow(keyText.getWindowToken(), 0);  
            }
            getSearch(typeGroup.getCheckedRadioButtonId(),keyText.getEditableText().toString());

            /*intent.setClass(SearchActivity.this, MainCar91Activity.class);
            startActivity(intent);*/
        }
    }
    
    private void getSearch(int type,String key){
        switch (type) {
        case R.id.search_item_repairshop:
            HttpHandler.httpHandler.getSearchRepairShop(1, key, callBackSearch);
            break;
        case R.id.search_item_article:
            HttpHandler.httpHandler.getSearchArticle(1, key, callBackSearch);
            break;
        case R.id.search_item_exposure:
            HttpHandler.httpHandler.getSearchExposure(1, key, callBackSearch);
            break;
        default:
            break;
        }
    }

    /*@Override
    protected void onResume() {
        // TODO Auto-generated method stub
        clearSearchInfo();
        super.onResume();
    }*/

    /*public static void clearSearchInfo(){
    	searchKey = null;
        item = null;
    }*/

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
    }
}
